package leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class l0347_前K个高频元素_1_全排序 {

    public int[] topKFrequent(int[] nums, int k) {
        int[] resultArr = new int[k];
        if (nums == null || nums.length == 0) {
            return resultArr;
        }
        Map<Integer, Integer> dataMap = new HashMap<>();
        for (int num : nums) {
            Integer count = dataMap.getOrDefault(num, 0);
            dataMap.put(num, count + 1);
        }
        Set<Map.Entry<Integer, Integer>> entries = dataMap.entrySet();
        Map.Entry<Integer, Integer>[] entryArr = new Map.Entry[entries.size()];
        entries.toArray(entryArr);
        Arrays.sort(entryArr, (Map.Entry<Integer, Integer> entry1, Map.Entry<Integer, Integer> entry2) -> {
            return entry2.getValue() - entry1.getValue();
        });
        for (int i = 0; i < k; i++) {
            resultArr[i] = entryArr[i].getKey();
        }
        return resultArr;
    }
}
